#include "../include/utils.h"
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>

string getHomeDir() {
    string homedir;

    if ((homedir = getenv("HOME")).c_str() == NULL) {
        homedir = getpwuid(getuid())->pw_dir;
    }

    return homedir;
}

string getTerminal() {
	return getenv("TERM");
}

string getConfigDirPath() {
    return getHomeDir() + "/.config/ellie";
}

void addItemToHistory(string name, string exec) {
    if (name.empty()) return;

    std::ofstream outfile;
    outfile.open(getConfigDirPath()+"/history", std::ios_base::app); // append instead of overwrite
    outfile << name + "|" + exec + "\n";
    outfile.close();
}

void makeConfigDir() {
    string configPath = getConfigDirPath();
    mkdir(configPath.c_str(), 0777);
}

bool stringToBool(string &oper) {
	if (oper == "True" || oper == "true") return true;
	return false;
}

void split(string &str, char delim, vector<string> &out) {
    size_t start;
    size_t end = 0;

    while ((start = str.find_first_not_of(delim, end)) != string::npos)
    {
        end = str.find(delim, start);
        out.push_back(str.substr(start, end - start));
    }
}

void splitCommand(string &command, vector<string> &out) {
	size_t space_pos = command.find(" ");

	if (space_pos != string::npos) {
		out.push_back(command.substr(0, space_pos));
		out.push_back(command.substr(space_pos + 1));
	}
}

bool isStringHasSpace(string &str) {
	size_t space_pos = str.find(" ");
	return space_pos != string::npos;
}

void launchApp(string &cmd) {
	if (isStringHasSpace(cmd)) {
		vector<string> out;
		splitCommand(cmd, out);

		const char *command = out[0].c_str();
		const char *args = out[1].c_str();

		CreateProcess(command, args);
	} else {
		const char *command = cmd.c_str();
		const char *args = "";

		CreateProcess(command, args);
	}
}

pid_t CreateProcess(const char* command, const char* parametersIn) {
    const int maxNumArgs = 1024;
    const char* args[maxNumArgs];
    char* parameters = NULL;

	freopen("/dev/null", "r", stdin);
	freopen("/dev/null", "w", stdout);
	freopen("/dev/null", "w", stderr);

    memset(args, 0, (sizeof(char*) * maxNumArgs));
    args[0] = command;

    if(parametersIn != NULL) {
        parameters = strdup(parametersIn);
        int strLen = strlen(parameters);

        int numParameters = 1;
        bool expectNextParam = true;
        int i;
        for(i = 0; i < strLen; i++) {
            if(parameters[i] == ' ' || parameters[i] == '\t' ||
               parameters[i] == '\n')
            {
                expectNextParam = true;
                parameters[i] = '\0';
            } else if(expectNextParam) {
                args[numParameters] = &(parameters[i]);
                numParameters++;
                expectNextParam = false;
            }
        }
    }

    pid_t pid = fork();
    if (pid == 0) {
		setsid();

		extern char **environ;

		if (command[0] == '/') 
			execve(command, (char**)args, environ);
		else
			execvpe(command, (char**)args, environ);
        _exit(1);
    }

    if(parameters != NULL)
        free(parameters);

	//waitpid(pid, NULL, 0);

    return pid;
}

